package com.echo.acc.service.img;

import com.echo.acc.framework.exception.AccException;
import com.echo.acc.service.TemplateFileReaderService;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author echo
 * date 2023-12-25 15:26:22
 **/
@Service
public class TemplateFileReaderServiceImpl implements TemplateFileReaderService {

    private final ResourceLoader resourceLoader;

    public TemplateFileReaderServiceImpl(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Override
    public String readTemplateFile(String filePath) {
        try {
            // 从类路径加载文件，假设文件都在 templates 目录下
            Resource resource = resourceLoader.getResource("classpath:templates/doc/" + filePath + ".md");
            // 获取文件输入流
            java.io.InputStream inputStream = resource.getInputStream();
            // 使用 Apache Commons IO 读取输入流内容为字符串
            return IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
            throw new AccException("Error reading the file. filePath: " + filePath);
        }
    }

}
